﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Runtime.InteropServices;
using DispatchAssist.Service;
using System.Configuration;

namespace DispatchAssist.AppHost
{
    public partial class frmMain : Form
    {
        #region Members.

        Dictionary<Guid, MdiUserControl> Mdis;
        AuthService authproxy;
        MenuStrip menuMain;
        public WaitForm wwf = new WaitForm();
        Sunisoft.IrisSkin.SkinEngine skinEngine1;

        #endregion

        #region Ctor.

        public frmMain()
        {
            InitializeComponent();
            authproxy = new AuthService();
            authproxy.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

            skinEngine1 = SkinConfig.Instance.EnsureSkin(this);

            this.tssWelcome.Text = string.Format("您好{0}，当前席位为{1}", AuthContext.Current.User.UserName, AuthContext.Current.Credentials.Find(c => c.CredentialType == CredentialType.Self).SeatName);
        
        }

        #endregion

        #region EventHandlers

        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                if (AuthContext.Current.User.RoleID == new Guid("00000000-0000-0000-0000-000000000000"))
                {
                    MessageBox.Show("当前用户没有分配角色,请管理员为你添加角色!");
                    return;
                }

                this.Mdis = ModuleHelper.LoadALLModules();
                this.CheckPower(ref Mdis);
                menuMain = ModuleHelper.CreateModuleMenu(Mdis.Values.ToList(), subMenu_Click);
                menuMain.Font = this.Font;
                this.Controls.Add(menuMain);
                this.notifyIcon.ContextMenuStrip = this.contextMenuStrip;

                // add check right at 2011-8-12 by wuzhongqi
                MdiUserControl defaultModule = ModulesConfiguration.GetConfig().DefaultModule;

                if (Mdis.Values.Where(f => f.ModuleID == defaultModule.ModuleID).Count() > 0)
                {
                    this.mdiTabCantainer1.AddMdiForm(defaultModule);
                }
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error(ex);

                MessageBox.Show("系统错误" + ex.Message + "\r\n" + ex.StackTrace);
                Application.Exit();
            }
        }

        private void tbtnChooseSkin_Click(object sender, EventArgs e)
        {
            ChooseSkin();
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!this.Visible)
            {
                this.Visible = true;
            }
        }

        void subMenu_Click(object sender, EventArgs e)
        {
            Guid id = (Guid)(sender as ToolStripMenuItem).Tag;
            this.mdiTabCantainer1.AddMdiForm(Mdis[id]);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (mdiTabCantainer1.TabCount > 0)
            {
                bool flag = false;
                TabPage tpI = null;
                foreach (TabPage tp in mdiTabCantainer1.TabPages)
                {
                    if (tp.Name == "tp_MeteoMsgAlert") { flag = true; tpI = tp; break; }

                }

                if (flag && (tpI.Controls[0] as MdiUserControl).CommonFun())
                {
                    MessageBox.Show("有预警信息没有处理,无法关闭！");
                    e.Cancel = true;
                    return;
                }
            }

            if (ConfigurationManager.AppSettings["ExitConfirm"] == "1")
            {
                if (e.CloseReason == CloseReason.UserClosing)
                {
                    if (DialogResult.No == MessageBox.Show("您确认要退出系统吗？\r\n（点击“否”系统将最小化到托盘）", "确认退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        e.Cancel = true;
                        this.Visible = false;
                        notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
                        notifyIcon.BalloonTipText = "辅助签派程序仍在运行，若需要退出，请在此点击右键";
                        notifyIcon.ShowBalloonTip(5000);
                    }
                }
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {

            try
            {
                //更新用户为登出状态
                Credential item = AuthContext.Current.Credentials.Where(f => f.CredentialType == CredentialType.Self).ToList()[0];
                authproxy.LogoutAsync(AuthContext.Current.User.UserID, item.SeatID);
            }
            catch
            {

            }
            finally
            {
                this.mdiTabCantainer1.Dispose();
                Application.Exit();
            }

        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        #endregion

        void CheckPower(ref Dictionary<Guid, MdiUserControl> Mdis)
        {
            Dictionary<Guid, SystemModule> dicmdi = null;
            Dictionary<Guid, MdiUserControl> validModule = new Dictionary<Guid, MdiUserControl>();

            dicmdi = authproxy.GetSystemModules().ToDictionary(s => s.ModuleID);

            foreach (var mdi in Mdis)
            {
                if (!((!dicmdi.ContainsKey(mdi.Key)) || ((dicmdi[mdi.Key].ModuleFlag) & AuthContext.Current.Role.PowerFlag) == 0))
                {
                    validModule.Add(mdi.Key, mdi.Value);
                }
            }

            Mdis = validModule;
        }

        void ChooseSkin()
        {
            frmChooseSkin cho = new frmChooseSkin();
            cho.ShowDialog();
            SkinConfig.Instance.UpdateSkin(this, skinEngine1);
        }
    }
}
